﻿using AntdUI;
using BST250301.Models;
using BST250301.Views;
using BST250301TestStand.Models;
using BST250301TestStand.Models.Helpers;
using BST250301TestStand.Models.Utils;
using OpenTK.Audio.OpenAL;
using System.Diagnostics;
using System.Reflection;
using System.Threading.Tasks;
using System.Windows.Forms;
using static BST250301TestStand.Models.Utils.PLCConfig;
using static BST250301TestStand.Models.Utils.TCUConfig;

namespace BST250301.Pages
{
    public partial class Manual : UserControl
    {
        private AntdUI.Window window;
        private MonitorModel monitor = MainWindow._monitorConfig;
        private ShowPLCStatusParm _plc;
        private ShowTCUStatusParm _tcu;
        private ShowNVHStatusParm _nvh;
        public Manual()
        {
            InitializeComponent();
            switch1.CheckedChanged += async (sender, e) => await switch1_CheckedChanged();
            PLCConfig.ShowPLCStatus += ShowPLC;
            TCUConfig.ShowTCUStatus += ShowTCU;
            NVHConfig.ShowNVHStatus += ShowNVH;
            InitData();
        }

        private void RecordTimer_Tick(object? sender, EventArgs e)
        {

        }

        private void InitData()
        {
            if (!MainWindow.userCurrent.ViewEnable)
            {
                this.Visible = false;
            }
            if (!MainWindow.userCurrent.OperEnable)
            {
                this.Enabled =false;
            }
            if (!MainWindow.userCurrent.ModifyEnable)
            {
                this.selectNVHSN.Enabled = false;
            }
            if (!MainWindow.userCurrent.DeleteEnable)
            {
                this.selectNVHSN.Enabled = false;
            }
            if (!MainWindow.userCurrent.IsSuperAdmin)
            {
                this.segmentedCFCRRNF.Enabled = false;
            }
            //selectTemperatureOil.Items.Clear();
            //var ret = Enum.GetValues(typeof(TOil));
            //foreach (var item in ret)
            //{
            //    selectTemperatureOil.Items.Add(item);
            //}
        }
        private void ShowPLC(object? sender, ShowPLCStatusParm plc)
        {
            this._plc = plc;
            if (this.InvokeRequired)
            {
                this.BeginInvoke(new EventHandler<ShowPLCStatusParm>(ShowPLC), sender, plc);
                return;
            }
            else
            {
                segmentedIsAuto.SelectIndex = plc.isAuto ? 1 : 0;
                segmentedSafe.SelectIndex = plc.isSafeStop ? 1 : 0;
                switchDriverIsConnect.Checked = plc.isDriverConnected;
                switchLoadIsConnect.Checked = plc.isLoadConnected;
                switchDriverIsStart.Checked = plc.isDriverStart;
                switchLoadIsStart.Checked = plc.isLoadStart;
                //switchPLCTempaSub.CheckedChanged += switchPLCTempaSub_CheckedChanged;
                //switchPLCTempaAdd.CheckedChanged += switchPLCTempaAdd_CheckedChanged;
                //switchPLCLoadConnect.CheckedChanged += switchPLCLoadConnect_CheckedChanged;
                //switchPLCDriverConnect.CheckedChanged += switchPLCDriverConnect_CheckedChanged;
                //switchPLCR.CheckedChanged += switchPLCR_CheckedChanged;
                //switchPLCD.CheckedChanged += switchPLCD_CheckedChanged;
                //switchPLCLoad.CheckedChanged += switchPLCLoad_CheckedChanged;
                //switchPLCDriver.CheckedChanged += switchStart_CheckedChanged;
                //switchCFCREn.CheckedChanged += switchCFCREn_CheckedChanged;
                //segmentedTranType.SelectIndexChanged += segmentedTranType_SelectIndexChanged;
                //switchPTO.CheckedChanged += switchPTO_CheckedChanged;
                //segmentedCFCRRNF.SelectIndexChanged += segmentedCFCRRNF_SelectIndexChanged;
                //switchPTOEn.CheckedChanged += switchPTOEn_CheckedChanged;
                //switchCPTOCHN.CheckedChanged += switchCPTOCHN_CheckedChanged;
                //switchCRCHN.CheckedChanged += switchCRCHN_CheckedChanged;
                //switchCFCHN.CheckedChanged += switchCFCHN_CheckedChanged;
            }
        }
        private void ShowTCU(object? sender, ShowTCUStatusParm tcu)
        {
            if (this.InvokeRequired)
            {
                this.BeginInvoke(new EventHandler<ShowTCUStatusParm>(ShowTCU), sender, tcu);
                return;
            }
            this._tcu = tcu;
            //this.sliderSPC_CF.Value = tcu.CF_FBCurrent;
            //this.sliderSPC_CR.Value = tcu.CR_FBCurrent;
            //this.sliderSPC_CPTO.Value = tcu.PTO_FBCurrent;
        }
        private void ShowNVH(object? sender, ShowNVHStatusParm nvh)
        {
            if (this.InvokeRequired)
            {
                this.BeginInvoke(new EventHandler<ShowNVHStatusParm>(ShowNVH), sender, nvh);
                return;
            }
            this._nvh = nvh;
            inputNVHResult.Text = nvh.DataStr;
        }
        private void buttonWarm_Click(object sender, EventArgs e)
        {
            DialogResult confirmResult = MessageBox.Show("确认启动？", "警告", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
            if (confirmResult != DialogResult.Yes)
                return;
            //if (selectTemperatureOil.SelectedIndex < 0)
            //{
            //    confirmResult = MessageBox.Show("请检查油温设置是否为正常值？", "警告", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
            //    return;
            //}
            //if (monitor == null || monitor.isEnableOil)
            //    return;
            //monitor.isEnableOil = true;
            //switch (selectTemperatureOil.SelectedIndex)
            //{
            //    case 0:
            //        break;
            //    case 1:
            //        monitor.SetOil(40, 3, 1);
            //        break;
            //    case 2:
            //        monitor.SetOil(40, 5, 2);
            //        break;
            //    case 3:
            //        monitor.SetOil(80, 3, 1);
            //        break;
            //    case 4:
            //        monitor.SetOil(80, 5, 2);
            //        break;
            //    default:
            //        break;
            //}
        }

        private void buttonEngine_Click(object sender, EventArgs e)
        {
            DialogResult confirmResult = MessageBox.Show("确认启动？", "警告", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
            if (confirmResult != DialogResult.Yes)
                return;


            // monitor.SetSpeed(speed, 50, 10);
        }

        private void buttonLoad_Click(object sender, EventArgs e)
        {
            DialogResult confirmResult = MessageBox.Show("确认启动？", "警告", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
            if (confirmResult != DialogResult.Yes)
                return;

            //monitor.SetSpeed(load, 3, 2);
        }

        private void label14_Click(object sender, EventArgs e)
        {

        }

        private void groupBox1_Enter(object sender, EventArgs e)
        {

        }

        private void buttonInit_Click(object sender, EventArgs e)
        {
            //要给PLC对接全部0


            switchCFCHN.Checked = false;
            switchCRCHN.Checked = false;
            switchCPTOCHN.Checked = false;

            sliderSPC_CF.Value = 0;
            sliderSPC_CR.Value = 0;
            sliderSPC_CPTO.Value = 0;

            sliderOilTemper.Value = 0;
            sliderRoateSpeed.Value = 0;
            sliderLoadSpeed.Value = 0;

            segmentedTranType.SelectIndex = 0;
            segmentedCFCRRNF.SelectIndex = 1;
            switchCFCREn.Checked = false;
            switchPTOEn.Checked = false;
            switchPTO.Checked = false;
        }

        private void switchStart_CheckedChanged(object sender, BoolEventArgs e)
        {
            var ret = Operation.PLCDriverStart(switchPLCDriver.Checked);
        }

        private void buttonOil_Click(object sender, EventArgs e)
        {
            var ret = Operation.SetOilTempa((float)sliderOilTemper.Value);
        }

        private void buttonSpeed_Click(object sender, EventArgs e)
        {
            if (this._tcu.CF_FBCurrent > 10 && this._tcu.CR_FBCurrent > 10)
            {
                var form = new ShowDialog("当前CF不可与CR同时存在电流，请重置");
                form.ShowDialog();// form.SetTopMost(this.Handle);
                //AntdUI.Modal.open(new AntdUI.Modal.Config("", form, TType.None)
                //{
                //    BtnHeight = 0,
                //});

                sliderRoateSpeed.Value = 0;

                return;
            }
            var ret = Operation.SetSpeed(new StepTest { ValueStart = sliderRoateSpeed.Value, ValueEnd = 0, StepKeep = 0, StepValue = 0 });
        }

        private void buttonTurqut_Click(object sender, EventArgs e)
        {
            if (this._tcu.CF_FBCurrent > 10 && this._tcu.CR_FBCurrent > 10)
            {
                var form = new ShowDialog("当前CF不可与CR同时存在电流，请重置");
                form.ShowDialog();//form.SetTopMost(this.Handle);
                //AntdUI.Modal.open(new AntdUI.Modal.Config("", form, TType.None)
                //{
                //    BtnHeight = 0,
                //});

                sliderLoadSpeed.Value = 0;

                return;
            }
            var ret = Operation.SetTorque(sliderLoadSpeed.Value);
        }

        private void switchPTOEn_CheckedChanged(object sender, BoolEventArgs e)
        {

        }

        private void switchPTO_CheckedChanged(object sender, BoolEventArgs e)
        {


        }

        private void switchCFCREn_CheckedChanged(object sender, BoolEventArgs e)
        {

        }

        private void segmentedCFCRRNF_SelectIndexChanged(object sender, IntEventArgs e)
        {

        }

        private void segmentedTranType_SelectIndexChanged(object sender, IntEventArgs e)
        {
            bool ret;
            if (segmentedTranType.SelectIndex == 0)
                ret = Operation.SetTransmitType(0x0);
            else if (segmentedTranType.SelectIndex == 1)
                ret = Operation.SetTransmitType(0x1);
            else if (segmentedTranType.SelectIndex == 2)
                ret = Operation.SetTransmitType(0x2);
        }

        private static byte setCurrentChan = 0x00;
        private void switchCFCHN_CheckedChanged(object sender, BoolEventArgs e)
        {

            if (switchCFCHN.Checked)
            {
                switchCRCHN.Checked = false;
            }
            setCurrentChan = switchCFCHN.Checked ? setCurrentChan += 0x01 : setCurrentChan -= 0x01;
            //Operation.SetCurrentChan((CurrentChannel)setCurrentChan);
        }

        private void switchCRCHN_CheckedChanged(object sender, BoolEventArgs e)
        {
            //statusByte = switchCRCHN.Checked ? DataTranslate.TurnOnSwitch(statusByte, 1) : DataTranslate.TurnOffSwitch(statusByte, 1);

            if (switchCRCHN.Checked)
            {
                switchCFCHN.Checked = false;
            }
            setCurrentChan = switchCRCHN.Checked ? setCurrentChan += 0x02 : setCurrentChan -= 0x02;
            //Operation.SetCurrentChan((CurrentChannel)setCurrentChan);
        }

        private void switchCPTOCHN_CheckedChanged(object sender, BoolEventArgs e)
        {
            //statusByte = switchCPTOCHN.Checked ? DataTranslate.TurnOnSwitch(statusByte, 2) : DataTranslate.TurnOffSwitch(statusByte, 2);

            if (switchCPTOCHN.Checked)
            {
            }
            setCurrentChan = switchCPTOCHN.Checked ? setCurrentChan += 0x04 : setCurrentChan -= 0x04;
            // Operation.SetCurrentChan((CurrentChannel)setCurrentChan);
        }


        private void button1_Click(object sender, EventArgs e)
        {
            var form = new ShowRealList(null, null,false);// { Size = new Size(800, 500) };
            AntdUI.Modal.open(new AntdUI.Modal.Config("", form, TType.None)
            {
                BtnHeight = 0,
            });
        }

        private void buttonCFC_Click(object sender, EventArgs e)
        {
            var ma = sliderSPC_CF.Value;
            if (ma > 10 && this._tcu.CR_FBCurrent > 10)
            {
                var form = new ShowDialog("当前CF不可与CR同时存在电流，请检查");
                form.SetTopMost(this.Handle);
                AntdUI.Modal.open(new AntdUI.Modal.Config("", form, TType.None)
                {
                    BtnHeight = 0,
                });

                sliderSPC_CF.Value = 0;

                return;
            }
            Operation.SetCurrenCF(ma);
            Operation.SetCurrentChan((CurrentChannel)setCurrentChan);
        }

        private void buttonCRC_Click(object sender, EventArgs e)
        {
            var ma = sliderSPC_CR.Value;
            if (ma > 10 && this._tcu.CF_FBCurrent > 10)
            {
                var form = new ShowDialog("当前CF不可与CR同时存在电流，请检查");
                form.SetTopMost(this.Handle);
                AntdUI.Modal.open(new AntdUI.Modal.Config("", form, TType.None)
                {
                    BtnHeight = 0,
                });

                sliderSPC_CR.Value = 0;

                return;
            }
            Operation.SetCurrenCR(ma);
            Operation.SetCurrentChan((CurrentChannel)setCurrentChan);
        }

        private void buttonCPTOC_Click(object sender, EventArgs e)
        {
            var ma = sliderSPC_CPTO.Value;
            Operation.SetCurrenCPTO(ma);
            Operation.SetCurrentChan((CurrentChannel)setCurrentChan);
        }

        private void switchPLCLoad_CheckedChanged(object sender, BoolEventArgs e)
        {
        }

        private void switchPLCD_CheckedChanged(object sender, BoolEventArgs e)
        {
            var ret = Operation.PLCD(switchPLCD.Checked);
        }

        private void switchPLCR_CheckedChanged(object sender, BoolEventArgs e)
        {
            var ret = Operation.PLCR(switchPLCR.Checked);
        }

        private void switchPLCDriverConnect_CheckedChanged(object sender, BoolEventArgs e)
        {
            if (switchPLCDriverConnect.Checked)
            {
                Operation.PLCDriverDisconnect(false);
                Operation.PLCDriverConnect(true);
            }
            else
            {
                Operation.PLCDriverConnect(false);
                Operation.PLCDriverDisconnect(true);
            }
        }

        private void switchPLCLoadConnect_CheckedChanged(object sender, BoolEventArgs e)
        {
            if (switchPLCLoadConnect.Checked)
            {
                Operation.PLCLoadDisconnect(false);
                Operation.PLCLoadConnect(true);
            }
            else
            {
                Operation.PLCLoadConnect(false);
                Operation.PLCLoadDisconnect(true);
            }
        }

        private void switchPLCTempaAdd_CheckedChanged(object sender, BoolEventArgs e)
        {
            var ret = Operation.PLCTempaAdd(switchPLCTempaAdd.Checked);
        }

        private void switchPLCTempaSub_CheckedChanged(object sender, BoolEventArgs e)
        {
            var ret = Operation.PLCTempaSub(switchPLCTempaSub.Checked);
        }
        private void RecordTimer_Tick()
        {

        }
        private async Task switch1_CheckedChanged()
        {
            if (switch1.Checked)
            {
                _item = new ProjectItem
                {
                    Name = "手动测试",
                    ListRecord = new List<RecordData> {
                        new RecordData{Name ="n_engines速度",AppName ="PumpSpeed" },
                        new RecordData{Name ="n_clutch速度",AppName ="TransmInSpeed" },
                        new RecordData{Name ="n_vehicle速度",AppName ="TransmOutSpeed" },
                        new RecordData{Name ="n_PTO速度",AppName ="PTOSpeed" },
                    },
                };
                IsRecording = true;
                var ret = await SaveDataListRecord();
                MessageBox.Show($"记录已保存到【{ret}】");
                if (File.Exists(ret))
                {
                    Process.Start(new ProcessStartInfo(ret) { UseShellExecute = true });
                }
            }
            else
                IsRecording = false;
        }
        private bool IsRecording = false;
        private ProjectItem _item;
        public List<string> _ListAllCloum = new List<string>();
        public List<string> _ListAllRecord = new List<string>();
        public List<CanLogEntry> _CanLogEntries = new List<CanLogEntry>();
        private async Task<string> SaveDataListRecord()
        {
            string tcuStr = string.Empty;
            string plcStr = string.Empty;

            _ListAllCloum = new List<string>();
            _ListAllRecord = new List<string>();
            _CanLogEntries = new List<CanLogEntry>();

            var units = string.Empty;
            var desc = string.Empty;
            foreach (RecordData record in this._item.ListRecord)
            {
                _ListAllCloum.Add(record.AppName);
            }
            var dtdatetime = DateTime.Now;
            var dtstart = dtdatetime.ToString("yyyy-MM-dd-HH-mm-ss-ffff");
            _ListAllRecord.Add($"测试项目：手动测试");
            _ListAllRecord.Add($"测试人：{MainWindow.configapp.LoginUser}  测试日期：{dtdatetime.ToString("yyyy-MM-dd HH:mm")}  测试结果：_____________");
            _ListAllRecord.Add($"数据组,日期,名称,代号,理论值,读取值,单位,备注");
            int tID = 0;
            await Task.Run(() =>
            {
                while (IsRecording)
                {
                    Thread.Sleep(5);
                    tID++;
                    var dttime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff");
                    try
                    {
                        //plc数据
                        if (this._plc != null)
                        {
                            Type typePLC = typeof(ShowPLCStatusParm);
                            PropertyInfo[] propertiesPLC = typePLC.GetProperties();
                            foreach (PropertyInfo prop in propertiesPLC)
                            {
                                if (_ListAllCloum.Contains(prop.Name))
                                {
                                    var rec = this._item.ListRecord.FirstOrDefault(name => name.AppName == prop.Name);
                                    rec.ReadValue = prop.GetValue(this._plc).ToString();
                                    _ListAllRecord.Add($"{tID},T{dttime},{rec.Name},{rec.ReportName},{rec.DefaultValue},{rec.ReadValue},{rec.Unit},");
                                }
                            }
                        }
                        //tcu数据
                        if (this._tcu != null)
                        {
                            var tcucan = new CanLogEntry
                            {
                                Timestamp = this._tcu.TimeStamp,
                                BusIndex = this._tcu.ID,
                                CanId = this._tcu.ID,
                                Direction = this._tcu.IsRx == "Tx" ? "Tx" : "Rx",
                                FrameType = this._tcu.IsStand == "false" ? "Remote" : "Data",
                                DataDlc = this._tcu.DataDlc,
                                DataStr = this._tcu.DataStr,
                            };
                            _CanLogEntries.Add(tcucan);

                            Type typeTCU = typeof(ShowTCUStatusParm);
                            PropertyInfo[] propertiesTCU = typeTCU.GetProperties();
                            foreach (PropertyInfo prop in propertiesTCU)
                            {
                                if (_ListAllCloum.Contains(prop.Name))
                                {
                                    var rec = this._item.ListRecord.FirstOrDefault(name => name.AppName == prop.Name);
                                    rec.ReadValue = prop.GetValue(this._tcu).ToString();
                                    _ListAllRecord.Add($"{tID},T{dttime},{rec.Name},{rec.ReportName},{rec.DefaultValue},{rec.ReadValue},{rec.Unit},");
                                }
                            }

                        }
                    }
                    catch (Exception ex)
                    {
                        return;
                    }
                }
            });
            //保存数据csv
            var ret = CSV.SaveProductList2CSV(_ListAllRecord, "D:\\Record\\", $"{this._item.Name}_Test_Data_{dtstart}.csv");
            string outputPath = $"D:\\Record\\TCU_{this._item.Name}_Data_{dtstart}.asc";
            CanLogGenerator.WriteToFile(outputPath, _CanLogEntries);
            return outputPath;
        }

        private void buttonBVHSend_Click(object sender, EventArgs e)
        {
            this.inputNVHResult.Text = string.Empty;
            Operation.SendNVHSNTest(this.selectNVHSN.Text, this.selectNVHTest.Text);
        }

        private void buttonAutoStartEngin_Click(object sender, EventArgs e)
        {
            Operation.StartOrStopEngineReady(true);

        }

        private void button2_Click(object sender, EventArgs e)
        {
            Operation.StartOrStopEngineReady(false);
        }

        private void buttonCPTO_Click(object sender, EventArgs e)
        {
            Operation.SetCPTOEn(switchPTOEn.Checked);
            Operation.SetCPTOOnOff(switchPTO.Checked);
        }

        private void buttonCFCR_Click(object sender, EventArgs e)
        {
            Operation.SetCFCREn(switchCFCREn.Checked);
            if (segmentedCFCRRNF.SelectIndex == 0)
                Operation.SetCFCRShp(ClutcCFCR.R);
            else if (segmentedCFCRRNF.SelectIndex == 1)
                Operation.SetCFCRShp(ClutcCFCR.N);
            else if (segmentedCFCRRNF.SelectIndex == 2)
                Operation.SetCFCRShp(ClutcCFCR.F);
        }

        private void segmentedDriverStartStop_SelectIndexChanged(object sender, IntEventArgs e)
        {
            if (!MainWindow.userCurrent.ApprovalEnable)
            {
                Process.GetCurrentProcess().Kill();

                //MessageBox.Show(window, "请输入新的注册码");
                return;
            }
            bool ret;
            if (segmentedDriverStartStop.SelectIndex == 0)
                ret = Operation.PLCDriverStart(true);
            else if (segmentedDriverStartStop.SelectIndex == 2)
                ret = Operation.PLCDriverStart(false);
        }

        private void segmentedDriverConnect_SelectIndexChanged(object sender, IntEventArgs e)
        {
            if (segmentedDriverConnect.SelectIndex == 0)
            {
                Operation.PLCDriverDisconnect(false);
                Operation.PLCDriverConnect(true);
            }
            else if (segmentedDriverConnect.SelectIndex == 2)
            {
                Operation.PLCDriverConnect(false);
                Operation.PLCDriverDisconnect(true);
            }
        }

        private void segmentedLoadStartStop_SelectIndexChanged(object sender, IntEventArgs e)
        {
            if (!MainWindow.userCurrent.ApprovalEnable)
            {
                Process.GetCurrentProcess().Kill();
                //MessageBox.Show(window, "请输入新的注册码");
                return;
            }
            bool ret;
            if (segmentedLoadStartStop.SelectIndex == 0)
                ret = Operation.PLCLoadStart(true);
            else if (segmentedLoadStartStop.SelectIndex == 2)
                ret = Operation.PLCLoadStart(false);
        }

        private void segmentedLoadConnect_SelectIndexChanged(object sender, IntEventArgs e)
        {
            if (segmentedLoadConnect.SelectIndex == 0)
            {
                Operation.PLCLoadDisconnect(false);
                Operation.PLCLoadConnect(true);
            }
            else if (segmentedLoadConnect.SelectIndex == 2)
            {
                Operation.PLCLoadConnect(false);
                Operation.PLCLoadDisconnect(true);
            }
        }

        private void buttonCFCRCPTO_Click(object sender, EventArgs e)
        {
            Operation.SetCurrentChan(0x00);
        }
        //private void buttonCurrentChn_Click(object sender, EventArgs e)
        //{
        //    Operation.SetCurrentChan(CurrentChannel.None);

        //    if (switchCFCHN.Checked)
        //        Operation.SetCurrentChan(CurrentChannel.CF);
        //    else if (switchCRCHN.Checked)
        //        Operation.SetCurrentChan(CurrentChannel.CR);
        //    if (switchCPTOCHN.Checked)
        //        Operation.SetCurrentChan(CurrentChannel.CPTO);
        //}

        //private void buttonCurrentChnCR_Click(object sender, EventArgs e)
        //{
        //    if (switchCPTOCHN.Checked)
        //        Operation.SetCurrentChan(CurrentChannel.CPTO);
        //}

        //private void buttonCurrentChnCPTO_Click(object sender, EventArgs e)
        //{
        //    if (switchCPTOCHN.Checked && switchCFCHN.Checked)
        //        Operation.SetCurrentChan(CurrentChannel.CPTOCF);
        //    else if (switchCPTOCHN.Checked && switchCRCHN.Checked)
        //        Operation.SetCurrentChan(CurrentChannel.CPTOCR);
        //    else if (switchCPTOCHN.Checked && switchCFCHN.Checked)
        //        Operation.SetCurrentChan(CurrentChannel.CPTOCF);
        //    else if (switchCPTOCHN.Checked && switchCFCHN.Checked)
        //        Operation.SetCurrentChan(CurrentChannel.CPTOCF);



        //}
    }
}